<div class="generic-instance-settings">
  {#if pushNotificationsSupport === false}
    <p>{intl.browserDoesNotSupportPush}</p>
  {:elseif $notificationPermission === "denied"}
    <p role="alert">{intl.deniedPush}</p>
  {:elseif $loggedInInstancesInOrder.length > 1}
    <p>{intl.pushNotificationsNote}</p>
  {/if}
  <form id="push-notification-settings"
        disabled="{!pushNotificationsSupport}"
        ref:form
        aria-label="{intl.pushSettings}">
    {#each options as option, i (option.key)}
      {#if i > 0}
        <br>
      {/if}
      <input type="checkbox"
             id="push-notifications-{option.key}"
             name="{option.key}"
             disabled="{!pushNotificationsSupport}"
             on:change="onPushSettingsChange(event)">
      <label for="push-notifications-{option.key}">{option.label}</label>
    {/each}
  </form>
</div>
<GenericInstanceSettingsStyle/>
<style>
  form[disabled="true"] {
    opacity: 0.5;
  }
  p {
    margin: 0 0 10px 0;
  }
</style>
<script>
  import GenericInstanceSettingsStyle from './GenericInstanceSettingsStyle.html'
  import { store } from '../../../_store/store.js'
  import { importShowTextConfirmationDialog } from '../../dialog/asyncDialogs/importShowTextConfirmationDialog.js'
  import { logOutOfInstance } from '../../../_actions/instances.js'
  import { updatePushSubscriptionForInstance, updateAlerts } from '../../../_actions/pushSubscription.js'
  import { toast } from '../../toast/toast.js'
  import { get } from '../../../_utils/lodash-lite.js'
  import { formatIntl } from '../../../_utils/formatIntl.js'

  export default {
    async oncreate () {
      const { instanceName, options } = this.get()
      await updatePushSubscriptionForInstance(instanceName)

      const { form } = this.refs
      const pushSubscription = this.store.getInstanceData(instanceName, 'pushSubscriptions')

      for (const { key } of options) {
        form.elements[key].checked = get(pushSubscription, ['alerts', key])
      }
    },
    store: () => store,
    data: () => ({
      options: [
        {
          key: 'follow',
          label: 'intl.newFollowers'
        },
        {
          key: 'favourite',
          label: 'intl.favorites'
        },
        {
          key: 'reblog',
          label: 'intl.reblogs'
        },
        {
          key: 'mention',
          label: 'intl.mentions'
        },
        {
          key: 'poll',
          label: 'intl.pollResults'
        },
        {
          key: 'status',
          label: 'intl.subscriptions'
        }
      ]
    }),
    computed: {
      pushNotificationsSupport: ({ $pushNotificationsSupport }) => $pushNotificationsSupport
    },
    methods: {
      async onPushSettingsChange (e) {
        const { instanceName, options } = this.get()
        const { form } = this.refs
        const alerts = {}

        for (const { key } of options) {
          alerts[key] = form.elements[key].checked
        }

        try {
          await updateAlerts(instanceName, alerts)
        } catch (err) {
          e.target.checked = !e.target.checked

          // TODO: Better way to detect missing authorization scope
          if (err.message.startsWith('403:')) {
            const showTextConfirmationDialog = await importShowTextConfirmationDialog()
            showTextConfirmationDialog({
              text: formatIntl('intl.needToReauthenticate', { instance: instanceName })
            }).on('positive', () => {
              /* no await */ logOutOfInstance(instanceName)
            })
          } else {
            toast.say(formatIntl('intl.failedToUpdatePush', {
              error: err.message || ''
            }))
          }
        }
      }
    },
    components: {
      GenericInstanceSettingsStyle
    }
  }
</script>
